<?php

add_action( 'admin_enqueue_scripts', 'hfr_source_enqueue');
function hfr_source_enqueue($hook) {
	
	if (isset($_GET['act']) && ($_GET['act'] == 'new' || $_GET['act'] == 'edit') 
		&& isset($_GET['page']) && $_GET['page'] == 'hfr_source_manager') {
		
		wp_enqueue_script( 'hfr-ajax-script', HFR_PATH .'includes/assets/js/hfr-source-form.js', array('jquery') );
	
		// in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
		wp_localize_script( 'hfr-ajax-script', 'hfr_ajax_object',
	            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
	}
}

// Check Sitemap ajax
add_action( 'wp_ajax_hfr_check_sitemap', 'hfr_check_sitemap_ajax' );

function hfr_check_sitemap_ajax() {
	$sitemap = $_POST['sitemap'];
	
	if (!empty($sitemap)) {
		$url = HFR_SERVER . "/rest/ajax/check-type-link?url=" . urlencode($sitemap);
		
		$content = hfr_remote_get($url);
		
		if ($content != null && $content != "") {
			echo $content;
		} else {
			echo 0;
		}
	} else {
		echo 0;
	}
	
	die;
}


//Check Link Selector ajax
add_action( 'wp_ajax_hfr_check_link_selector', 'hfr_check_link_selector_ajax' );

function hfr_check_link_selector_ajax() {
	//$data = $_REQUEST['data'];
	$params = array();
	parse_str($_REQUEST['data'], $params);
	
	if ($params['linkSelecterJs'] != "") {
		$params['linkSelecterJs'] = base64_decode($params['linkSelecterJs']);
	}

	$url = HFR_SERVER . "/rest/ajax/show-link";
	
	$content = hfr_remote_post($url, $params);
	
	if ($content != null && $content != "") {
		echo $content;
	}
	
	die;
}

//Preview content
add_action( 'wp_ajax_hfr_preview', 'hfr_preview_ajax' );

function hfr_preview_ajax() {
	$params = array();
	parse_str($_REQUEST['data'], $params);
	
	/*
	$params['title-selecter'] = $params['titleSelecter'];
	$params['content-selecter'] = $params['contentSelecter'];
	$params['remove-selecter'] = $params['removeSelecter'];
	$params['custom-selecter'] = $params['customSelecter'];
	*/
	if ($params['linkSelecterJs'] != "") {
		$params['linkSelecterJs'] = base64_decode($params['linkSelecterJs']);
	}
	
	if ($params['customSelecter'] != "") {
		$params['customSelecter'] = base64_decode($params['customSelecter']);
	}
	
	$url = HFR_SERVER . "/rest/ajax/preview";
	$content = hfr_remote_post($url, $params);

	if ($content != null && $content != "") {
		echo $content;
	}
	
	die;
}